﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.Bll;

public partial class UserControls_CarbonFootprintQuestion_Transport_Cars : CarbonExchange.WebControls.AuditQuestionBase
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        rblCarShare.SelectedIndexChanged += new EventHandler(rblCarShare_SelectedIndexChanged);
        rptCars.ItemAdded += new EventHandler<CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs>(rptCars_ItemAdded);
        rptCars.ItemRemoved += new EventHandler<CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs>(rptCars_ItemRemoved);
    }

    void rptCars_ItemRemoved(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        phExtras.Visible = rptCars.Items.Count() > 0;
    }

    void rptCars_ItemAdded(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        phExtras.Visible = true;
    }

    void rblCarShare_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlPeople.Visible = lblNoPeople.Visible = rblCarShare.SelectedValue == "1";
        //txtNoPeople.Visible = lblNoPeople.Visible = rblCarShare.SelectedValue == "1";
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public override void DataBind()
    {
        var noCars = Answer.GetSetting<int>("rptCars");
        rptCars.SetNumberOfItems(noCars);
        
        phExtras.Visible = noCars > 0;

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblServiced")))
            rblServiced.Text = Answer.GetSetting<string>("rblServiced");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblAirCon")))
            rblAirCon.Text = Answer.GetSetting<string>("rblAirCon");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblCarShare")))
            rblCarShare.Text = Answer.GetSetting<string>("rblCarShare");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblEcoDriving")))
            rblEcoDriving.Text = Answer.GetSetting<string>("rblEcoDriving");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblTyresInflatedCorrectly")))
            rblTyresInflatedCorrectly.Text = Answer.GetSetting<string>("rblTyresInflatedCorrectly");
        ddlPeople.Text = Answer.GetSetting<string>("ddlPeople");
        //txtNoPeople.Text = Answer.GetSetting<string>("txtNoPeople");

        rblCarShare_SelectedIndexChanged(rblCarShare, EventArgs.Empty);

        base.DataBind();
    }

    protected void rptCars_ItemDataBinding(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        var ameeCarType = e.Item.FindControl("ameeCarType") as CarbonExchange.WebControls.AmeeDrillDown;
        var txtCarDistance = e.Item.FindControl("txtCarDistance") as TextBox;
        var ddlCarDistance = e.Item.FindControl("ddlCarDistance") as DropDownList;
        if (ameeCarType != null && txtCarDistance != null && ddlCarDistance != null)
        {
            ameeCarType.AddOptions(Answer.GetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>(string.Concat("ameeCarType_", e.Item.ItemIndex)));
            txtCarDistance.Text = Answer.GetSetting<string>(string.Format("txtCarDistance_{0}", e.Item.ItemIndex));
            ddlCarDistance.Text = Answer.GetSetting<string>(string.Format("ddlCarDistance_{0}", e.Item.ItemIndex));
        }
    }

    protected void ameeCar_LabelDataBound(object sender, CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "fuel")
        {
            e.Label.Text = GetText("Fuel");
        }
        else if (e.DataCatagory.ChoiceName == "size")
        {
            e.Label.Text = GetText("Engine");
        }
    }

    protected override bool SaveQuestion()
    {
        var completed = true;
        List<AnswerItem> itemsToKeep = new List<AnswerItem>();
        AmeeProfileItemFactory factory = new AmeeProfileItemFactory();

        //save car settings and all car settings
        Answer.SetSetting("rptCars", rptCars.Items.Count());
        Answer.SetSetting<string>("rblServiced", rblServiced.Text);
        Answer.SetSetting<string>("rblAirCon", rblAirCon.Text);
        Answer.SetSetting<string>("rblCarShare", rblCarShare.Text);
        Answer.SetSetting<string>("rblEcoDriving", rblEcoDriving.Text);
        Answer.SetSetting<string>("rblTyresInflatedCorrectly", rblTyresInflatedCorrectly.Text);
        Answer.SetSetting<string>("txtNoPeople", ddlPeople.Text);
        //Answer.SetSetting<string>("txtNoPeople", txtNoPeople.Text);

        //if cars are regualrly serviced
        var serviced = rblServiced.Text == "1";

        //if user useulally uses eaircon
        var airCon = rblAirCon.Text == "1";

        //if user regualarly use aircon
        var ecoDriving = rblEcoDriving.Text == "1";

        //if cars are generally dirven with types at correct air pressure
        var tyresInflatedCorrectly = rblTyresInflatedCorrectly.Text == "1";
        //if cars are generaly diven with more than one person in car
        int noOfPeople = 1;
        if (rblCarShare.SelectedValue == "1" && rptCars.Items.Count() > 0)
        {
            try
            {
                noOfPeople = int.Parse(ddlPeople.Text);
                //noOfPeople = int.Parse(txtNoPeople.Text);
            }
            catch(FormatException)
            {
                completed = false;
            }
        }


        foreach (var item in rptCars.Items)
        {
            var itemName = string.Format("Car_{0}", item.ItemIndex);
            var ameeCarType = item.FindControl("ameeCarType") as CarbonExchange.WebControls.AmeeDrillDown;
            var txtCarDistance = item.FindControl("txtCarDistance") as TextBox;
            var ddlCarDistance = item.FindControl("ddlCarDistance") as DropDownList;
            if (ameeCarType != null && txtCarDistance != null && ddlCarDistance != null)
            {
                Answer.SetSetting(string.Format("ameeCarType_{0}", item.ItemIndex), ameeCarType.SelectedOptions);
                Answer.SetSetting(string.Format("txtCarDistance_{0}", item.ItemIndex), txtCarDistance.Text);
                Answer.SetSetting(string.Format("ddlCarDistance_{0}", item.ItemIndex), ddlCarDistance.SelectedValue);
                if (ameeCarType.CurrentCategory.DataItemSelected)
                {
                    var profileItem = EnsureProfileItem(itemName, factory, ameeCarType.CurrentCategory);

                    decimal distancePerYear = 0;
                    try
                    {
                        distancePerYear = decimal.Parse(txtCarDistance.Text);
                    }
                    catch (FormatException)
                    {
                        completed = false;
                    }

                    //if drop down is miles convert mils to km
                    if(ddlCarDistance.SelectedValue == "miles")
                    {
                        distancePerYear = distancePerYear * 1.609344m; 
                    }

                    //convert distance per year to distance per month
                    var distancePerMonth = distancePerYear / 12m;

                    //save if id is not set
                    bool save = string.IsNullOrEmpty(profileItem.Id);

                    if (profileItem.GetValue<decimal>("distanceKmPerMonth") != distancePerMonth)
                    {
                        profileItem.SetValue<decimal>("distanceKmPerMonth", distancePerMonth);
                        save = true;
                    }

                    if(profileItem.GetValue<bool>("regularlyServiced") != serviced)
                    {
                        profileItem.SetValue<bool>("regularlyServiced", serviced);
                        save = true;
                    }

                    if (profileItem.GetValue<bool>("airconFull") != airCon)
                    {
                        profileItem.SetValue<bool>("airconFull", airCon);
                        save = true;
                    }

                    if (profileItem.GetValue<bool>("ecoDriving") != ecoDriving)
                    {
                        profileItem.SetValue<bool>("ecoDriving", ecoDriving);
                        save = true;
                    }

                    //nb switch tyresInflatedCorrectly to tyresUnderinflated setting
                    if (profileItem.GetValue<bool>("tyresUnderinflated") != !tyresInflatedCorrectly)
                    {
                        profileItem.SetValue<bool>("tyresUnderinflated", !tyresInflatedCorrectly);
                        save = true;
                    }


                    if (profileItem.GetValue<decimal>("occupants") != noOfPeople)
                    {
                        profileItem.SetValue<decimal>("occupants", noOfPeople);
                        save = true;
                    }

                    if (save)
                    {
                        factory.Save(profileItem);
                    }

                    itemsToKeep.Add(Answer.SetItem(itemName, profileItem));
                    if(!(distancePerMonth > 0))
                    {
                        completed = false;
                    }
                }
                else
                {
                    itemsToKeep.Add(Answer.SetItem(itemName, ameeCarType.CurrentCategory));
                    completed = false;
                }
            }
            else
            {
                completed = false;
            }
        }


        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    public override int GetActiveItemsCount()
    {
        var i = 1;
        if (phExtras.Visible)
            i += phExtras.Controls.OfType<Panel>().Count();
        return i;
    }

    public override int RenderItems(int start, int end, HtmlTextWriter writer)
    {
        var items = new List<Panel>();
        items.Add(pnlCars);
        if (phExtras.Visible)
            items.AddRange(phExtras.Controls.OfType<Panel>());
        int i = 0;
        foreach (var panel in items.Skip(start).Take(end - start))
        {
            panel.RenderControl(writer);
            i++;
        }
        return i;
    }
}
